package com.hanbang.taitaigou.ui.activity.gouwuche;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.DbGwcData;
import com.hanbang.taitaigou.model.GetUserAddressList;
import com.hanbang.taitaigou.model.SaveOrder;
import com.hanbang.taitaigou.ui.activity.aboutme.address.AboutMeAddressManagemenntActivity;
import com.hanbang.taitaigou.ui.activity.application.MyApplication;
import com.hanbang.taitaigou.ui.activity.base.MainBaseActivity;
import com.hanbang.taitaigou.ui.activity.home.MainActivity;
import com.hanbang.taitaigou.ui.activity.login.LogInActivity;
import com.hanbang.taitaigou.ui.widget.NumberSelectView;
import com.hanbang.taitaigou.ui.widget.dialog.BaseDialog;
import com.hanbang.taitaigou.ui.widget.dialog.DialogTimeSelect;
import com.hanbang.taitaigou.ui.widget.dialog.OnClickCallback;
import com.hanbang.taitaigou.ui.widget.swipemenulistview.SwipeMenu;
import com.hanbang.taitaigou.ui.widget.swipemenulistview.SwipeMenuCreator;
import com.hanbang.taitaigou.ui.widget.swipemenulistview.SwipeMenuItem;
import com.hanbang.taitaigou.ui.widget.swipemenulistview.SwipeMenuListView;
import com.hanbang.taitaigou.utils.db.GwcDbUtil;
import com.hanbang.taitaigou.utils.http.BitmapUtil;
import com.hanbang.taitaigou.utils.http.HttpCallBack;
import com.hanbang.taitaigou.utils.http.HttpLocalUtils;
import com.hanbang.taitaigou.utils.http.HttpRequestParams;
import com.hanbang.taitaigou.utils.http.JsonHelper;
import com.hanbang.taitaigou.utils.other.StringUtils;
import com.hanbang.taitaigou.utils.ui.ToastUtils;
import com.hanbang.taitaigou.utils.ui.UiUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;


/**
 * 21.0	根据订单ID获取订单信息
 * Created by fanxin on 2016/3/26.
 */
public class GouWuCheActivity extends MainBaseActivity {


    public static String ACTION_NAME = "ACTION_NUMBER";


    //地址的ID
    private int Address_id = -1;
    //收货时间
    private String shouhuoTime;

    //主页面
    private RelativeLayout rl_gwc;
    //副页面
    private FrameLayout fl_gwc;
    //去逛逛
    private Button bt_qgg;


    private double bb;

    private List<DbGwcData> list = new ArrayList<DbGwcData>();

    private List<GetUserAddressList>listAddress = new ArrayList<>();

    private ListViewAdapyer listViewAdapyer;


    private SaveOrder saveOrder = null;

    private ImageView gwc;
    private TextView tv_gwc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gouwuche);
        initView();
        moRenAddress();
        setOnClickListener();

        IntentFilter intentFilter = new IntentFilter(GwcDbUtil.GWC_CHANG_ADD);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG_SUB);
        intentFilter.addAction(GwcDbUtil.GWC_CHANG);
        intentFilter.addAction("ChangeAddress");
        intentFilter.addAction("sengAddress");
        intentFilter.addAction("upAddress");
        intentFilter.addAction("gaiAddress");
        intentFilter.addAction(LogInActivity.FINISH_FLAG);
        registerReceiver(broadcastReceiver, intentFilter);



    }


    /**
     * 获取广播
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(LogInActivity.FINISH_FLAG)){
                moRenAddress();
            }else if(intent.getAction().equals("upAddress")){
                moRenAddress();
            }else if(intent.getAction().equals("sengAddress")){
                moRenAddress();
            }else if(intent.getAction().equals("gaiAddress")){
                moRenAddress();
            }
            setAllJiage();
        }
    };


    /*
     * 设置点击事件
     */
    private void setOnClickListener() {
        bt_settlement.setOnClickListener(onClickListener);
        ll_receipt_address.setOnClickListener(onClickListener);
        bt_qgg.setOnClickListener(onClickListener);
    }

    @SuppressWarnings("unused")
    private View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {
                //选好了
                case R.id.bt_settlement:
                    saveOrder();

                    break;
                //地址选择
                case R.id.ll_receipt_address:
                    if (!isLogin(true)) {

                    } else {
                        intent.putExtra("addressType", "1");
                        intent.setClass(GouWuCheActivity.this, AboutMeAddressManagemenntActivity.class);
                        startActivityForResult(intent, 999);
                    }
                    break;
                //去逛逛
                case R.id.bt_qgg:
//                    Intent intent = new Intent(this, MainActivity.class);
                    intent.setClass(GouWuCheActivity.this, MainActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 收货时间的点击事件
     */
    @Event(value = R.id.shsjLL)
    private void shshOnClick(View view) {
        DialogTimeSelect dialogTimeSelect = new DialogTimeSelect(this);
        dialogTimeSelect.setClickCallback(new OnClickCallback() {
            @Override
            public void onClick(BaseDialog dialog, Object number, Object content) {
                shouhuoTime = number.toString() + content.toString();
                shsjTv.setText("收货时间：" + number.toString() + content.toString());
            }
        });
        dialogTimeSelect.show();
    }

    /**
     * 地址回调
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999 && resultCode == RESULT_OK) {
            Address_id = data.getIntExtra("id", Address_id);
            tv_name.setText("姓名：" + data.getStringExtra("name"));
            tv_tel.setText("电话：" + data.getStringExtra("phone"));
            tv_address.setText("收货地址：" + data.getStringExtra("sf") + data.getStringExtra("city") + data.getStringExtra("quyu") + data.getStringExtra("xiangAddress"));
            setAddressVisible();
        }
    }


    /**
     * 设置地址是否显示
     */
    private void setAddressVisible() {
        if (Address_id < 0) {
            tv_select_address.setVisibility(View.VISIBLE);
            ll_select_address.setVisibility(View.GONE);
            tv_name.setText("");
            tv_tel.setText("");
            tv_address.setText("");
        } else {
            tv_select_address.setVisibility(View.GONE);
            ll_select_address.setVisibility(View.VISIBLE);
        }
    }

    /*
     * 初始化view
     */
    private void initView() {
        tv_gwc = (TextView)findViewById(R.id.tv_gwc);
        tv_gwc.setTextColor(getResources().getColor(R.color.black));
        gwc = (ImageView)findViewById(R.id.gwc);
        gwc.setImageResource(R.mipmap.gwc_1);


        // 设置顶部的标题
        setTop(null, 0, getString(R.string.top_order_details), null, 0);
        setCurrentBotton(4);

        ll_receipt_address = (LinearLayout) findViewById(R.id.ll_receipt_address);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_tel = (TextView) findViewById(R.id.tv_tel);
        lvfsv_list = (SwipeMenuListView) findViewById(R.id.lvfsv_list);
        tv_total = (TextView) findViewById(R.id.tv_total);
        bt_settlement = (Button) findViewById(R.id.bt_settlement);
        tv_select_address = (TextView) findViewById(R.id.tv_select_address);
        ll_select_address = (LinearLayout) findViewById(R.id.ll_select_address);
        et_message = (EditText) findViewById(R.id.et_message);
        bt_qgg = (Button) findViewById(R.id.bt_qgg);
        fl_gwc = (FrameLayout) findViewById(R.id.fl_gwc);
        rl_gwc = (RelativeLayout) findViewById(R.id.rl_gwc);




        listViewAdapyer = new ListViewAdapyer();
        lvfsv_list.setAdapter(listViewAdapyer);

        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
//                // create "open" item
//                SwipeMenuItem openItem = new SwipeMenuItem(
//                        getApplicationContext());
//                // set item background
//                openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
//                        0xCE)));
//                // set item width
//                openItem.setWidth(dp2px(90));
//                // set item title
//                openItem.setTitle("Open");
//                // set item title fontsize
//                openItem.setTitleSize(18);
//                // set item title font color
//                openItem.setTitleColor(Color.WHITE);
//                // add to menu
//                menu.addMenuItem(openItem);

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set a icon
                deleteItem.setIcon(R.mipmap.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

        // set creator
        lvfsv_list.setMenuCreator(creator);

        // step 2. listener item click event
        lvfsv_list.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
//                        list.remove(position);
                        GwcDbUtil.delete(list.get(position));
//                        list.remove(position);
                        list = GwcDbUtil.getDbGoods();
                        listViewAdapyer.notifyDataSetChanged();
                        break;
                }
            }
        });


    }


    /**
     * 获取购车商品信息
     */

    private void getCartGoodsInfo() {
        list = GwcDbUtil.getDbGoods();
        if (list == null) {
            list = new ArrayList<>();
        }
        listViewAdapyer.notifyDataSetChanged();
    }

    /**
     * 20.0	保存订单
     */
    private void saveOrder() {
        if (list == null || list.size() == 0) {
            ToastUtils.showShort(this, "您的购物车空空如也");
            return;
        }
        if (Address_id == -1) {
            ToastUtils.showShort(this, "请选择收货地址");
            return;
        }
        if (StringUtils.isBlank(shouhuoTime)) {
            ToastUtils.showShort(this, "请选择收货时间");
            return;
        }

        BaseDialog dialog = new BaseDialog(this, BaseDialog.MODE.CONFIRM);
        dialog.setTitleMain("提示");
        dialog.setContent("您确定挑选好商品了吗?");
        dialog.setQuxiao("再选选吧");
        dialog.setConfirm("前去支付");
        dialog.setConfirmColor(getResources().getColor(R.color.blue));
        dialog.setOnClickCallback(new OnClickCallback() {
            @Override
            public void onClick(BaseDialog dialog, Object number, Object content) {
                if ((int) number == 2) {
                    HttpRequestParams httpRequestParams = new HttpRequestParams("SaveOrder");
                    httpRequestParams.addUserId(userData);
                    httpRequestParams.addBodyParameter("deadline", shouhuoTime);
                    httpRequestParams.addBodyParameter("storeID", String.valueOf(MyApplication.shangjiaId));
                    httpRequestParams.addBodyParameter("Address_id", String.valueOf(Address_id));
                    httpRequestParams.addBodyParameter("message", et_message.getText().toString());
                    httpRequestParams.addBodyParameter("goods_items", GwcDbUtil.getGwcToJson());
                    httpManager.post(httpRequestParams, new HttpCallBack<String>(GouWuCheActivity.this, "正在提交...") {
                        @Override
                        public void onSuccess(String result) {
                            super.onSuccess(result);
                            //"status": 0,
                            //"msg": "对不起，商品总结不满28元！"
                            /**
                             * "status": 1,
                             "order_id": 198,
                             "order_no": "DD16032917302970"
                             */
                            try {
                                JSONObject json = new JSONObject(result);
                                if (json.getInt("status") == 1) {
                                    saveOrder = JsonHelper.parseObject(json, SaveOrder.class);
                                    GwcDbUtil.clearAllGwc();
                                    clearBiao();
                                    Intent intent = new Intent();
                                    intent.putExtra("order_id", saveOrder.getOrder_id());
                                    String ss = tv_total.getText().toString().substring(3);
                                    intent.putExtra("zongjia", Double.parseDouble(ss));
                                    intent.putExtra("order_on", saveOrder.getOrder_no());
                                    intent.setClass(GouWuCheActivity.this, AboutMyOrderCommitActivity.class);
                                    startActivity(intent);
                                } else {
                                    ToastUtils.showShort(GouWuCheActivity.this, json.getString("msg"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    });
                }
            }
        });
        dialog.show();

    }


    class ListViewAdapyer extends BaseAdapter {

        @Override
        public int getCount() {
            if (list.size() > 0) {
                fl_gwc.setVisibility(View.GONE);
                rl_gwc.setVisibility(View.VISIBLE);

            } else {
                fl_gwc.setVisibility(View.VISIBLE);
                rl_gwc.setVisibility(View.GONE);
            }
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {

            // 常见的优化ViewHolder
            final ViewHolder viewHolder;
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = UiUtils.getInflaterView(GouWuCheActivity.this, R.layout.item_my_order_details);
                viewHolder.iv_photo = (ImageView) convertView.findViewById(R.id.iv_photo);
                viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                viewHolder.number_select_view = (NumberSelectView) convertView.findViewById(R.id.number_select_view);
                viewHolder.root = convertView;
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            //获取数据
            imageManager.bind(viewHolder.iv_photo, HttpLocalUtils.getHttpFileUrl(list.get(position).getImgUrl()), BitmapUtil.getImageOptionsBuilder().build());
            viewHolder.tv_name.setText(list.get(position).getName());
            viewHolder.number_select_view.setNumber(list.get(position).getSelectNumber());
            viewHolder.number_select_view.setOnItemClickListener(new NumberSelectView.OnItemClickListener() {
                @Override
                public boolean onAddClick(int num, NumberSelectView view) {
                    if (GwcDbUtil.addGoodAutoNumber(list.get(position))) {
                        listViewAdapyer.notifyDataSetChanged();
                        return true;
                    }
                    return false;
                }

                @Override
                public boolean onSubClick(int num, NumberSelectView view) {
                    if (GwcDbUtil.subGoodAutoNumber(list.get(position))) {
                        if (list.get(position).getSelectNumber() <= 0) {
//                            UiUtils.deleteItemAnimationRotationX(viewHolder.root, list, position, lvfsv_list);
                            list.remove(position);
                        }
                        listViewAdapyer.notifyDataSetChanged();
                        return true;
                    }
                    return false;
                }

            });

            return convertView;
        }

        class ViewHolder {
            private ImageView iv_photo;
            private TextView tv_name;
            private NumberSelectView number_select_view;
            private View root;
        }
    }

    @Override
    public void setBackArrows(View back) {
        super.setBackArrows(back);
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
    }


    @Override
    protected void onResume() {
        super.onResume();
        getCartGoodsInfo();
        setAllJiage();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }


    /**
     * 设置总价
     */
    private void setAllJiage() {
        tv_total.setText("总价：" + StringUtils.roundDouble(GwcDbUtil.getGwcAlltMoney(GwcDbUtil.SELL_PRICE), 2));
    }

    /**
     * 清空其他选择的地方
     */
    private void clearBiao() {
        Address_id = -1;
        shsjTv.setText("收货时间");
        shouhuoTime = null;
        et_message.setText("");
        setAddressVisible();
    }


    //地址选择
    private LinearLayout ll_receipt_address;
    private TextView tv_select_address;
    private LinearLayout ll_select_address;
    //收货地址
    private TextView tv_address;
    //姓名
    private TextView tv_name;
    //电话
    private TextView tv_tel;
    //商品明细
    private SwipeMenuListView lvfsv_list;
    //总价
    private TextView tv_total;
    //提交订单
    private Button bt_settlement;
    //用户输入的备注
    private EditText et_message;

    //收货时间
    @ViewInject(R.id.shsj)
    private TextView shsjTv;


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    /**
     * 获取用户的默认地址
     */
    private void moRenAddress(){
        HttpRequestParams httpRequestParams = new HttpRequestParams("GetUserAddressList");
        httpRequestParams.addUserId(userData);
        httpManager.post(httpRequestParams, new HttpCallBack<String>(this,null) {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray js = jsonObject.getJSONArray("result");

                    listAddress.clear();
                    if(js.length()>0){
                        listAddress.addAll(JsonHelper.parseCollection(js, ArrayList.class, GetUserAddressList.class));
                        Address_id = listAddress.get(0).getId();
                        String name = listAddress.get(0).getPurchname();
                        String tel = listAddress.get(0).getPurchtel();
                        String address = listAddress.get(0).getProvince() + listAddress.get(0).getCity() + listAddress.get(0).getArea() + listAddress.get(0).getAddress();
                        setAddress(name,tel,address);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void setAddress(String name,String tel,String address){
        tv_name.setText("姓名："+name);
        tv_tel.setText("电话："+tel);
        tv_address.setText("收货地址："+address);
        tv_select_address.setVisibility(View.GONE);
        ll_select_address.setVisibility(View.VISIBLE);
    }
}
